import { getCitys } from "../../api/app"

const MAX_LENGTH = 15

function insertArr(value: any, state: any) {
    let addressArr: [] = state.addressHistory;
    const index = addressArr.findIndex((item: any) => item.name === value?.name)
    if (index > 0) {
        addressArr.splice(index, 1);
    } else if (index == 0) {
        return
    }
    value && addressArr.unshift(value as never)
    if (addressArr.length > MAX_LENGTH) {
        addressArr.pop()
    }
    return addressArr
}

const app = {
    state: {
        citys: JSON.parse(sessionStorage.getItem("X-Citys") as string) || "",
        hotCity: JSON.parse(sessionStorage.getItem("X-HotCity") as string) || "",
        guessCity: JSON.parse(sessionStorage.getItem("X-GuessCity") as string) || "",
        cityId: sessionStorage.getItem("X-CityId") || "",
        addressHistory: JSON.parse(localStorage.getItem("X-AddressHistory") as string) || []
    },
    mutations: {
        SET_CITYS(state: any, value: Object) {
            state.citys = value
            sessionStorage.setItem("X-Citys", JSON.stringify(value))
        },
        SET_HOTCITY(state: any, value: Object) {
            state.hotCity = value
            sessionStorage.setItem("X-HotCity", JSON.stringify(value))
        },
        SET_GUESSCITY(state: any, value: Object) {
            state.guessCity = value
            sessionStorage.setItem("X-GuessCity", JSON.stringify(value))
        },
        SET_CITYID(state: any, id: number) {
            state.cityId = id
            sessionStorage.setItem("X-CityId", id.toString())
        },
        SET_ADRHISTORE(state: any, history: []) {
            state.addressHistory = history;
            localStorage.setItem("X-AddressHistory", JSON.stringify(state.addressHistory));
        }
    },
    actions: {
        GetCitys({ commit }: any) {
            return new Promise(resolve => {
                getCitys("group").then((res: any) => {
                    commit('SET_CITYS', res)
                })
            })
        },
        GetHotCity({ commit }: any) {
            return new Promise(resolve => {
                getCitys("hot").then((res: any) => {
                    commit('SET_HOTCITY', res)
                })
            })
        },
        GetGuessCity({ commit }: any) {
            return new Promise(resolve => {
                getCitys("guess").then((res: any) => {
                    commit('SET_GUESSCITY', res)
                })
            })
        },
        GenarateCityId({ commit }: any, cityId: number) {
            commit('SET_CITYID', cityId)
        },
        SaveAdrHistory({ state, commit }: any, history: Object) {
            const accessHistory = insertArr(history, state)
            commit('SET_ADRHISTORE', accessHistory)
        }
    }
}

export default app